package com.lxz.datasource.config.bean;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.SQLException;

@Component
public class InitProject implements ApplicationRunner {

    public static boolean masterStatus = true;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        new Thread(new DataSourceMasterTask()).start();
    }

    public static boolean validateConnectionMaster() {
        DruidDataSource bean = (DruidDataSource) SpringBeanUtil.getBean("master", DataSource.class);
        try {
            DruidPooledConnection connection = bean.getConnection(3000);
            bean.validateConnection(connection);
        } catch (SQLException throwables) {
            System.out.println("数据库 【master】 连接异常！");
            throwables.printStackTrace();
            return false;
        }
        return true;
    }

    class DataSourceMasterTask implements Runnable {

        @Override
        public void run() {
            while (true) {
                if (!masterStatus) {
                    masterStatus = validateConnectionMaster();
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ignored) {
                }
            }
        }


    }
}
